/*
 * @Author: your name
 * @Date: 2021-10-19 13:52:15
 * @LastEditTime: 2021-10-19 15:09:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /a1902-a-group/vue_router/src/store/index.js
 */
import { createStore } from 'vuex'
import {myLogin} from '../api/login'
import Cookies from 'js-cookie';
import {filterRouter} from '../utils/filterRouter'
import {userRouter} from '../router/userRouter'
import router from '../router'
export default createStore({
  state: {
    user: {}, // 用户信息
    author: Cookies.get('author') || '', // 权限key
    routerList: [], // 获取路由表
  },
  mutations: {
    // 存储用户信息
    getUser(state, payload) {
      state.user = {...payload};
      state.author = payload.author;
      Cookies.set('author', payload.author)
    },
    // 存储获取的路由信息
    getRouterList(state, payload) {
      state.routerList = payload;
    }
  },
  actions: {
    async LOGIN({commit, dispatch}, payload) {
      const data = await myLogin('/login', payload);
      console.log(data)
      // 存储 token
      Cookies.set('token', data.data.token);
      // 获取路由表
      await dispatch('GET_ROUTER', data.data.user.author);
      // 存储用户信息
      await commit('getUser', data.data.user)
    },
    // 动态获取路由表的
    async GET_ROUTER({commit}, payload) {
      // 筛选路由表
      const routers = filterRouter(userRouter, payload);
      routers.forEach((item) => {
        // 将我们获取到的每一个路由push到router里面
        router.addRoute(item);
      })
      // 跳路由
      router.push(routers[0].path);
      await commit('getRouterList', routers)
    }
  },
  modules: {
  }
})
